package 并发编程16.实际运用场景;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author idea
 * @data 2019/2/10
 */
public class Student implements Runnable, Delayed {

    private String name;

    /**
     * 交卷时间
     */
    private long submitTime;

    /**
     * 是否已经交卷
     */
    private boolean isForce = false;

    /**
     * 工作时间
     */
    private long workTime;

    private CountDownLatch countDownLatch;


    public Student(String name, long submitTime,CountDownLatch countDownLatch) {
        super();
        this.name = name;
        workTime = submitTime;
        this.countDownLatch=countDownLatch;
        //都转为转为ns
        this.submitTime = TimeUnit.NANOSECONDS.convert(submitTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    public boolean isForce() {
        return isForce;
    }

    public void setForce(boolean force) {
        isForce = force;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(submitTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == null || !(o instanceof Student)) {
            return 1;
        }
        if (o == this) {
            return 0;
        }
        Student s = (Student) o;
        if (this.workTime > s.workTime) {
            return 1;
        } else if (this.workTime == s.workTime) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public void run() {
        if (isForce) {
            System.out.println(name + " 交卷, 希望用时" + workTime + "分钟"+" ,实际用时 120分钟" );
        }else {
            System.out.println(name + " 交卷, 希望用时" + workTime + "分钟"+" ,实际用时 "+workTime +" 分钟");
        }
        countDownLatch.countDown();
    }
}
